<template>
  <div class="page-main" v-title :data-title="dataTitle?dataTitle:'基建现场管理单列表'">
    <FixedMenu/>
    <home-nav :userData="userinfo"></home-nav>
    <div class="banner"><span>基建现场管理单</span></div>
    <div class="container">
      <div class="header" style="padding: 10px 0px">
        <a-row type="flex" justify="space-between" align="middle">
          <a-col :xl="{ span: 14 }" :lg="{ span: 11 }">
            <a-button class="hte-btn add-btn" type="primary" @click="handleAdd">创建</a-button>
            <a-button class="hte-btn" plain @click="handleEdit">编辑</a-button>
            <a-button class="hte-btn" plain @click="handleExport">导出</a-button>
            <a-button class="hte-btn" plain @click="handleDel" style="color: red">删除</a-button>
            <a-button class="hte-btn" plain @click="handleCancel" style="color: red">作废</a-button>
            <a-button class="hte-btn" plain @click="handleReload">刷新</a-button>
          </a-col>
          <a-col :xl="{ span: 9 }" :lg="{ span: 13 }" class="input-ground">
            <a-input-group compact>
              <a-select v-model="keywordType" @change="changeKeywordType">
                <a-select-option value="1"> 单据流水号 </a-select-option>
                <a-select-option value="2"> 单据名称 </a-select-option>
              </a-select>
              <a-input-search
                v-if="keywordType == '1'"
                v-model="searchForm.applyNo"
                @search="handleToSearch"
                placeholder="请按照关键字进行搜索"
              />
              <a-input-search
                v-if="keywordType == '2'"
                v-model="searchForm.name"
                @search="handleToSearch"
                placeholder="请按照关键字进行搜索"
              />
            </a-input-group>
            <a-button class="hte-btn del-btn" @click="showSearchForm = true">高级搜索</a-button>
          </a-col>
        </a-row>
        <a-modal
          :visible="showSearchForm"
          width="70vw"
          :bodyStyle="{ padding: '10px' }"
          title="高级查询"
          @ok="handleToSearch"
          @cancel="showSearchForm = false"
        >
          <a-form-model
            ref="ruleForm"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            @keyup.enter.native="handleToSearch"
          >
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="单据状态">
                  <a-select  mode="multiple" v-model="searchForm.statusList" style="width: 100%" allowClear>
                    <a-select-option value=""> 全部 </a-select-option>
                    <a-select-option
                      v-for="(code, index) in codes.InfrastructureStatus"
                      :key="index"
                      :value="code.code"
                    >
                      {{ code.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据流水号">
                  <a-input allow-clear v-model="searchForm.applyNo" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据名称">
                  <a-input allow-clear v-model="searchForm.name" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="采购订单号">
                  <a-input allow-clear v-model="searchForm.poNo" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同编号">
                  <a-input allow-clear v-model="searchForm.contractNumber" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="供应商">
                  <a-input allow-clear v-model="searchForm.supplierName" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="申请人">
                  <a-input allow-clear v-model="searchForm.applyUser" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据类型">
                  <a-select v-model="searchForm.type" style="width: 100%" allowClear>
                    <a-select-option value=""> 全部 </a-select-option>
                    <a-select-option v-for="(code, index) in codes.InfrastructureType" :key="index" :value="code.code">
                      {{ code.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="作废状态">
                  <a-select v-model="searchForm.isCancel" style="width: 100%" allowClear>
                    <a-select-option value="-1"> 全部 </a-select-option>
                    <a-select-option v-for="(code, index) in CancelStatus" :key="index" :value="code.code">
                      {{ code.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="合同名称">
                  <a-input allow-clear v-model="searchForm.contractName" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="签订公司">
                  <a-input allow-clear v-model="searchForm.companyName" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-modal>
      </div>
      <div class="floatNav">
        <!-- <div class="budget-detail" @click="toMyTask">
          <span class="iconfont icon-reportReserve"></span>
          <a-badge :offset="[-11, -15]">
            <p>我的报工单</p>
          </a-badge>
        </div> -->
        <!-- <div class="budget-detail">
          <span class="iconfont icon-reportReserve"></span>
          <a-badge count="22" :offset="[-11, -15]">
            <p>验收付款单</p>
          </a-badge>
        </div> -->
      </div>
      <div class="content-list">
        <a-table
          :scroll="{ x: 1800 }"
          :columns="columns"
          :data-source="records"
          rowKey="id"
          bordered
          :pagination="false"
          :customRow="customRow"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <span slot="applyNoRender" slot-scope="text, record">
            <span class="font-active" @click="toDetail(record)">
              {{ record.applyNo }}
            </span>
          </span>
          <template slot="handlerStepRender" slot-scope="text, record">
            <span v-if="record.status == '1'">
              {{ record.handlerStep }}
            </span>
          </template>
          <template slot="statusRender" slot-scope="text, record">
            <a-tooltip>
              <template #title>状态不对?点我更新</template>
              <a-icon type="sync" @click="updateStatus(record.id)" />
            </a-tooltip>
            <template v-for="item in codes.InfrastructureStatus">
              <template v-if="item.code == record.status">
                {{ item.name }}
              </template>
            </template>
            <templete v-if="record.isCancel == '1'"> （已作废） </templete>
          </template>
          <template slot="typeRender" slot-scope="text, record">
            <template v-for="item in codes.InfrastructureType">
              <template v-if="item.code == record.type">
                {{ item.name }}
              </template>
            </template>
          </template>
          <template slot="docTypeRender" slot-scope="text, record">
            <template v-for="item in codes.InfrastructureDocType">
              <template v-if="item.code == record.docType">
                {{ item.name }}
              </template>
            </template>
          </template>
          <template slot="supplierRender" slot-scope="text, record">
            {{ record.supplierName + '/' + record.supplierCode }}
          </template>
          <template slot="applyTimeRender" slot-scope="text, record">
            {{ formatDate(record.applyTime, 'yyyy-MM-dd') }}
          </template>
          <template slot="currentHandlerRender" slot-scope="text, record">
            {{ currentHandlerRenderFunc(record) }}
          </template>
        </a-table>
        <a-pagination
          show-size-changer
          :default-current="1"
          :total="searchForm.total"
          @change="pageChange"
          @showSizeChange="onShowSizeChange"
          :show-total="(total) => `共 ${total} 条记录`"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { formatDate, parseTime } from '@/utils/util'
import { UtilsMixin } from '@/mixins/UtilsMixin'
import { Modal } from 'ant-design-vue'
export default {
  mixins: [UtilsMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    FixedMenu: () => import('@/views/workReport/home/FixedMenu')
  },
  data() {
    return {
      dataTitle:this.$route?this.$route.name:"",
      currUserId: this.$store.getters.userInfo.username,
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      urls: {
        list: '/infrastructure/page',
        myPermission: '/workReport/project/myPermission',
        codes: '/manage/codeInfo/queryByTypes',
        delete: '/infrastructure/delete',
        changeCancelStatus: '/infrastructure/changeCancelStatus',
        updateStatus: '/infrastructure/updateStatus',
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      keywordType: '1',
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      searchForm: {
        pageNo: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        total: 0,
        isCancel: 0,
      },
      codes: {},
      records: [],
      columns: [
        {
          title: '单据状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'statusRender' },
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '当前步骤',
          dataIndex: 'handlerStep',
          scopedSlots: { customRender: 'handlerStepRender' },
          width: '100px',
          align: 'left',
          ellipsis: true,
        },
        {
          title: '当前处理人/接收时间/停留时间',
          dataIndex: 'handlerUser',
          scopedSlots: { customRender: 'currentHandlerRender' },
          width: '230px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '单据流水号',
          dataIndex: 'applyNo',
          align: 'center',
          width: '130px',
          ellipsis: true,
          scopedSlots: { customRender: 'applyNoRender' },
        },
        {
          title: '合同名称',
          dataIndex: 'contractName',
          align: 'center',
          width: '230px',
          ellipsis: true,
        },
        {
          title: '单据名称',
          dataIndex: 'name',
          align: 'center',
          width: '230px',
          ellipsis: true,
        },
        {
          title: '公文类型',
          dataIndex: 'docType',
          align: 'center',
          width: '130px',
          ellipsis: true,
          scopedSlots: { customRender: 'docTypeRender' },
        },
        {
          title: '单据类型',
          dataIndex: 'type',
          align: 'center',
          width: '130px',
          ellipsis: true,
          scopedSlots: { customRender: 'typeRender' },
        },
        {
          title: '单据编号',
          dataIndex: 'num',
          align: 'center',
          width: '130px',
          ellipsis: true,
        },
        {
          title: '申报金额',
          dataIndex: 'amount',
          align: 'center',
          width: '130px',
          ellipsis: true,
        },
        {
          title: '审批金额',
          dataIndex: 'auditAmount',
          align: 'center',
          width: '130px',
          ellipsis: true,
        },
        {
          title: '合同编号',
          dataIndex: 'contractNumber',
          align: 'center',
          width: '130px',
          ellipsis: true,
        },
        {
          title: '签订公司',
          dataIndex: 'companyName',
          align: 'center',
          width: '200px',
          ellipsis: true,
        },
        {
          title: '供应商名称/编码',
          dataIndex: 'supplierName',
          align: 'center',
          width: '230px',
          ellipsis: true,
          scopedSlots: { customRender: 'supplierRender' },
        },
        {
          title: '申请人',
          dataIndex: 'applyUser',
          align: 'center',
          width: '100px',
          ellipsis: true,
        },
        {
          title: '申请日期',
          dataIndex: 'applyTime',
          align: 'center',
          width: '130px',
          ellipsis: true,
          scopedSlots: { customRender: 'applyTimeRender' },
        },
      ],
      showSearchForm: false,
      selectedRowKeys: [],
      selectedRows: [],
      permission: [],
      CancelStatus: [
        { code: 0, name: '未作废' },
        { code: 1, name: '已作废' },
      ],
    }
  },
  async mounted() {
    this.fetchList()
    await this.fetchCodes()
    this.fetchPermission()
  },
  methods: {
    formatDate,
    changeKeywordType() {
      if (this.keywordType == '1') {
        this.$set(this.searchForm, 'name', '')
      } else {
        this.$set(this.searchForm, 'applyNo', '')
      }
    },
    fetchCodes() {
      let types = []
      types.push('InfrastructureStatus')
      types.push('InfrastructureType')
      types.push('InfrastructureDocType')
      getAction(this.urls.codes, { types: types.join(',') }).then((res) => {
        if (res.success) {
          this.codes = { ...this.codes, ...res.result }
        }
      })
    },
    fetchPermission() {
      getAction(this.urls.myPermission, { projectId: '-1' }).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = false
      if (this.permission && powers) {
        for (let p of powers) {
          if (this.permission.indexOf(p) > -1) {
            hasPower = true
            break
          }
        }
      }
      return hasPower
    },
    handleToSearch() {
      this.searchForm.pageNo = 1
      this.showSearchForm = false
      this.fetchList()
    },
    fetchList() {
      postAction(this.urls.list, this.searchForm).then((res) => {
        if (res.success) {
          this.records = res.result.records
          this.$set(this.searchForm, 'total', res.result.total)
        } else {
          this.$messageWorkReport.error('查询基建现场数据错误:' + res.message)
        }
      })
    },
    handleAdd() {
      this.windowOpen('/infrastructure/add' )
    },
    handleEdit() {
      if (!this.selectedRows || this.selectedRows.length <= 0) {
        return this.$messageWorkReport.warning('请选择一条记录操作')
      }
      this.windowOpen('/infrastructure/edit/' + this.selectedRows[0].id);
    },
    toDetail(record) {
      this.windowOpen('/infrastructure/edit/' + record.id );
    },
    handleCancel() {
      let that = this
      if (!this.selectedRows || this.selectedRows.length != 1) {
        return this.$messageWorkReport.warning('请选择一条记录操作')
      }
      if (this.selectedRows[0].isCancel == 1) {
        Modal.confirm({
          content: `当前选择记录已为作废记录，继续将取消作废，是否确认`,
          onOk: () => {
            getAction(that.urls.changeCancelStatus + '?id=' + that.selectedRowKeys.join(',')).then((res) => {
              if (res.success) {
                that.selectedRows = []
                that.selectedRowKeys = []
                that.$messageWorkReport.success('取消作废成功')
                that.fetchList()
              } else {
                that.$messageWorkReport.error('取消作废失败:' + res.message)
              }
            })
          },
        })
      } else {
        Modal.confirm({
          content: `请问是否确认作废此单据`,
          onOk: () => {
            that.confirmDelProcess()
            // getAction(that.urls.changeCancelStatus + '?id=' + that.selectedRowKeys.join(',')).then((res) => {
            //   if (res.success) {
            //     that.$messageWorkReport.success('作废单据成功')
            //     that.fetchList()
            //   } else {
            //     that.$messageWorkReport.error('作废单据失败:' + res.message)
            //   }
            // })
          },
        })
      }
    },
    confirmDelProcess() {
      let that = this
      Modal.confirm({
        content: `删除单据将会同时删除为完结流程,保留流程请点击【保留】,确认删除流程请点击【删除】,流程删除后将不可恢复`,
        okText: '保留',
        cancelText: '删除',
        onOk: () => {
          getAction(that.urls.changeCancelStatus + '?delProcess=0&id=' + that.selectedRowKeys.join(',')).then((res) => {
            if (res.success) {
              that.selectedRows = []
              that.selectedRowKeys = []
              that.$messageWorkReport.success('作废成功')
              that.fetchList()
            } else {
              that.$messageWorkReport.error('作废失败:' + res.message)
            }
          })
        },
        onCancel: () => {
          getAction(that.urls.changeCancelStatus + '?delProcess=1&id=' + that.selectedRowKeys.join(',')).then((res) => {
            if (res.success) {
              that.selectedRows = []
              that.selectedRowKeys = []
              that.$messageWorkReport.success('作废成功')
              that.fetchList()
            } else {
              that.$messageWorkReport.error('作废失败:' + res.message)
            }
          })
        },
      })
    },

    handleDel() {
      if (!this.selectedRows || this.selectedRows.length <= 0) {
        return this.$messageWorkReport.warning('请选择一条记录操作')
      }
      let applyNos = []
      for (let r of this.selectedRows) {
        applyNos.push(r.applyNo)
        if (r.status == '2') {
          return this.$messageWorkReport.warning('请勿删除审批通过的基建现场管理单')
        }
        if ([1, 3].indexOf(r.status) >= 0 && r.applyUserId == this.currUserId) {
          return this.$messageWorkReport.warning('审批中或审批不通过只能由流程发起人执行删除')
        }
      }
      let that = this
      Modal.confirm({
        content: `是否确定删除基建现场管理单[${applyNos.join(',')}]？`,
        onOk: () => {
          getAction(that.urls.delete + '?id=' + that.selectedRowKeys.join(',')).then((res) => {
            if (res.success) {
              that.selectedRows = []
              that.selectedRowKeys = []
              that.$messageWorkReport.success('删除成功')
              that.fetchList()
            } else {
              that.$messageWorkReport.error('删除失败:' + res.message)
            }
          })
        },
      })
    },
    handleReload() {
      this.fetchList()
    },
    handleExport() {
      this.searchForm.selectedIds = this.selectedRowKeys.join(',')
      let url = process.env.VUE_APP_API_BASE_URL + '/infrastructure/export?1=1'
      this.handleExportXls(parseTime(new Date(), '{y}{m}{d}') + '《基建现场管理单据列表》', url, this.searchForm)
    },
    pageChange(pageNo, pageSize) {
      this.$set(this.searchForm, 'pageSize', pageSize)
      this.$set(this.searchForm, 'pageNo', pageNo)
      this.fetchList()
    },
    onShowSizeChange(pageNo, pageSize) {
      this.searchForm.pageNo = 1
      this.searchForm.pageSize = pageSize
      this.fetchList()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    customRow(record) {
      return {
        on: {
          dblclick: (event) => {
            if (!this.selectedRowKeys) {
              this.selectedRowKeys = []
              this.selectedRows = []
            }
            if (this.selectedRowKeys.indexOf(record.id) <= -1) {
              this.selectedRows.push(record)
              this.selectedRowKeys.push(record.id)
            } else {
              let index = this.selectedRowKeys.indexOf(record.id)
              this.selectedRowKeys.splice(index, 1)
              this.selectedRows.splice(index, 1)
            }
          },
        },
      }
    },
    currentHandlerRenderFunc(record) {
      let text = ''
      if (record.handlerUser) {
        if (record.handlerTime) {
          text = record.handlerUser + '/' + record.handlerTime + '/' + record.stayDays + '天'
          // var startDate = new Date(record.handlerTime).getTime()
          // var endDate = new Date().getTime()
          // var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000)
          // text += '/' + parseInt(days) + '天'
        }
      }
      return text
    },
    updateStatus(id) {
      getAction(this.urls.updateStatus + '?id=' + id).then((res) => {
        if (res.success) {
          this.$messageWorkReport.success('更新成功')
          this.fetchList()
        } else {
          this.$messageWorkReport.error('更新失败')
        }
      })
    },
  },
  watch: {},
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.page-main {
  .container {
    .content {
      margin-top: 20px;
      section {
        margin-bottom: 18px;
        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }
          /deep/ .a-upload__input {
            display: none !important;
          }
        }
      }
    }
  }
  .tips-box {
    margin-top: 32px;
    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}
/deep/ .el-upload__input {
  display: none !important;
}
</style>
